<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>API调试页面</title>
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .debug-section {
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .log-area {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="container mt-4">
        <h1 class="mb-4">🔧 API调试页面</h1>
        
        <!-- 连接测试 -->
        <div class="debug-section">
            <h5>🌐 连接测试</h5>
            <div class="row">
                <div class="col-md-6">
                    <button id="testHealthBtn" class="btn btn-primary me-2">测试健康检查</button>
                    <button id="testRegionsBtn" class="btn btn-success me-2">测试地区API</button>
                    <button id="testCategoriesBtn" class="btn btn-info">测试分类API</button>
                </div>
                <div class="col-md-6">
                    <div id="status" class="alert alert-secondary">等待测试...</div>
                </div>
            </div>
        </div>

        <!-- 下拉菜单测试 -->
        <div class="debug-section">
            <h5>📋 下拉菜单测试</h5>
            <div class="row">
                <div class="col-md-6">
                    <label for="townshipSelect" class="form-label">乡镇街道</label>
                    <select class="form-select" id="townshipSelect">
                        <option value="">请选择乡镇街道</option>
                    </select>
                    <button id="loadTownshipsBtn" class="btn btn-primary mt-2">重新加载</button>
                </div>
                <div class="col-md-6">
                    <label for="categorySelect" class="form-label">线索分类</label>
                    <select class="form-select" id="categorySelect">
                        <option value="">请选择线索分类</option>
                    </select>
                    <button id="loadCategoriesBtn" class="btn btn-primary mt-2">重新加载</button>
                </div>
            </div>
        </div>

        <!-- 日志区域 -->
        <div class="debug-section">
            <h5>📝 调试日志</h5>
            <div id="logArea" class="log-area"></div>
            <button id="clearLogBtn" class="btn btn-outline-secondary btn-sm mt-2">清空日志</button>
        </div>

        <!-- 表单提交测试 -->
        <div class="debug-section">
            <h5>📤 表单提交测试</h5>
            <form id="testForm">
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">姓名</label>
                        <input type="text" class="form-control" name="name" value="测试用户" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">电话</label>
                        <input type="tel" class="form-control" name="phone" value="13800138000" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">乡镇街道</label>
                        <select class="form-select" name="township" required>
                            <option value="">请选择</option>
                            <option value="1">测试街道</option>
                        </select>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">线索标题</label>
                    <input type="text" class="form-control" name="title" value="测试线索标题" required>
                </div>
                <div class="mb-3">
                    <label class="form-label">案情描述</label>
                    <textarea class="form-control" name="content" rows="3" required>这是一个测试的案情描述，用于测试表单提交功能是否正常工作。</textarea>
                </div>
                <button type="submit" class="btn btn-warning">🧪 测试提交</button>
            </form>
        </div>
    </div>

    <script>
        // API配置
        const API_URLS = [
            'http://localhost:3001/api',
            'http://127.0.0.1:3001/api',
            'http://localhost:3000/api'
        ];
        
        let currentApiUrl = API_URLS[0];
        
        // DOM元素
        const elements = {
            status: document.getElementById('status'),
            logArea: document.getElementById('logArea'),
            townshipSelect: document.getElementById('townshipSelect'),
            categorySelect: document.getElementById('categorySelect'),
            testForm: document.getElementById('testForm')
        };
        
        // 日志函数
        function log(message, type = 'info') {
            const timestamp = new Date().toLocaleTimeString();
            const color = type === 'error' ? 'text-danger' : type === 'success' ? 'text-success' : 'text-primary';
            elements.logArea.innerHTML += `<div class="${color}">[${timestamp}] ${message}</div>`;
            elements.logArea.scrollTop = elements.logArea.scrollHeight;
            console.log(`[${timestamp}] ${message}`);
        }
        
        // 状态显示
        function showStatus(message, type = 'info') {
            const alertClass = type === 'error' ? 'alert-danger' : type === 'success' ? 'alert-success' : 'alert-info';
            elements.status.className = `alert ${alertClass}`;
            elements.status.textContent = message;
        }
        
        // 测试不同的API地址
        async function testApiUrl(url, endpoint = '') {
            try {
                log(`测试API地址: ${url}${endpoint}`);
                const response = await fetch(`${url}${endpoint}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    log(`✅ API响应成功: ${response.status}`, 'success');
                    return { success: true, data };
                } else {
                    log(`❌ API响应失败: ${response.status} ${response.statusText}`, 'error');
                    return { success: false, status: response.status };
                }
            } catch (error) {
                log(`❌ API连接失败: ${error.message}`, 'error');
                return { success: false, error: error.message };
            }
        }
        
        // 测试健康检查
        async function testHealth() {
            showStatus('正在测试健康检查...', 'info');
            
            for (const url of API_URLS) {
                const result = await testApiUrl(url, '/health');
                if (result.success) {
                    currentApiUrl = url;
                    showStatus(`✅ 健康检查成功! 使用API: ${url}`, 'success');
                    return true;
                }
            }
            
            showStatus('❌ 所有API地址都无法连接', 'error');
            return false;
        }
        
        // 测试地区API
        async function testRegions() {
            showStatus('正在测试地区API...', 'info');
            
            const result = await testApiUrl(currentApiUrl, '/regions?parent_id=0');
            if (result.success) {
                showStatus(`✅ 地区API成功! 获取到 ${result.data.data?.length || 0} 条记录`, 'success');
                log(`地区数据: ${JSON.stringify(result.data, null, 2)}`);
                
                // 填充下拉菜单
                if (result.data.data && result.data.data.length > 0) {
                    populateSelect(elements.townshipSelect, result.data.data);
                }
                return true;
            } else {
                showStatus('❌ 地区API失败', 'error');
                return false;
            }
        }
        
        // 测试分类API
        async function testCategories() {
            showStatus('正在测试分类API...', 'info');
            
            const result = await testApiUrl(currentApiUrl, '/clue-categories');
            if (result.success) {
                showStatus(`✅ 分类API成功! 获取到 ${result.data.data?.length || 0} 条记录`, 'success');
                log(`分类数据: ${JSON.stringify(result.data, null, 2)}`);
                
                // 填充下拉菜单
                if (result.data.data && result.data.data.length > 0) {
                    populateSelect(elements.categorySelect, result.data.data, 'name', 'name');
                }
                return true;
            } else {
                showStatus('❌ 分类API失败', 'error');
                return false;
            }
        }
        
        // 填充选择框
        function populateSelect(selectElement, options, valueField = 'id', textField = 'name') {
            // 保留第一个选项
            const placeholder = selectElement.options[0];
            selectElement.innerHTML = '';
            selectElement.appendChild(placeholder);
            
            options.forEach(option => {
                const optionElement = document.createElement('option');
                optionElement.value = option[valueField];
                optionElement.textContent = option[textField];
                selectElement.appendChild(optionElement);
            });
            
            log(`✅ 选择框已更新，添加了 ${options.length} 个选项`, 'success');
        }
        
        // 测试表单提交
        async function testSubmit(formData) {
            showStatus('正在测试表单提交...', 'info');
            
            const submitData = {
                user_info: {
                    name: formData.get('name'),
                    phone: formData.get('phone'),
                    township: formData.get('township'),
                    is_anonymous: false
                },
                clue_info: {
                    category: '经济犯罪',
                    title: formData.get('title'),
                    content: formData.get('content')
                }
            };
            
            try {
                log(`提交数据: ${JSON.stringify(submitData, null, 2)}`);
                
                const response = await fetch(`${currentApiUrl}/clues`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(submitData)
                });
                
                const result = await response.json();
                
                if (response.ok) {
                    showStatus(`✅ 表单提交成功! 线索编号: ${result.data?.clue_no}`, 'success');
                    log(`提交结果: ${JSON.stringify(result, null, 2)}`, 'success');
                } else {
                    showStatus(`❌ 表单提交失败: ${result.message}`, 'error');
                    log(`提交失败: ${JSON.stringify(result, null, 2)}`, 'error');
                }
            } catch (error) {
                showStatus(`❌ 提交错误: ${error.message}`, 'error');
                log(`提交错误: ${error.message}`, 'error');
            }
        }
        
        // 事件绑定
        document.getElementById('testHealthBtn').addEventListener('click', testHealth);
        document.getElementById('testRegionsBtn').addEventListener('click', testRegions);
        document.getElementById('testCategoriesBtn').addEventListener('click', testCategories);
        document.getElementById('loadTownshipsBtn').addEventListener('click', testRegions);
        document.getElementById('loadCategoriesBtn').addEventListener('click', testCategories);
        document.getElementById('clearLogBtn').addEventListener('click', () => {
            elements.logArea.innerHTML = '';
        });
        
        elements.testForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const formData = new FormData(this);
            testSubmit(formData);
        });
        
        // 页面加载时自动测试
        document.addEventListener('DOMContentLoaded', function() {
            log('🚀 API调试页面加载完成');
            log('📡 开始自动测试API连接...');
            
            setTimeout(async () => {
                if (await testHealth()) {
                    await testRegions();
                    await testCategories();
                }
            }, 1000);
        });
    </script>
</body>
</html> 